package sys.knot.integration.util;

import javax.inject.Singleton;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import java.sql.Connection;

@Singleton
public class DatabaseFiller {

    private boolean filled = false;

    public void ensureDummyData() {
        if (!filled) {
            addDummyData("db1");
            addDummyData("db3");
            filled = true;
        } else {
            System.out.println("Dummy data already loaded.");
        }
    }

    private void addDummyData(String name) {
        System.out.println("Adding dummy data to " + name);
        try {
            InitialContext initialContext = new InitialContext();
            DataSource ds = (DataSource) initialContext.lookup("java:jboss/datasources/" + name);
            Connection connection = ds.getConnection();
            connection.prepareStatement("CREATE TABLE data_table( " +
                            "id INT PRIMARY KEY, " +
                            "s1 VARCHAR(255), " +
                            "s2 VARCHAR(255), " +
                            "i1 INT, " +
                            "i2 INT, " +
                            "d1 DATE, " +
                            "d2 DATE " +
                            ");"
            ).executeUpdate();

            for (int i=10; i < 30; i++) {
                connection.prepareStatement("INSERT INTO data_table values (" +
                                i +
                                ", 'val_" + i + "'" +
                                ", 'val_" + (100+i) + "'" +
                                ", " + i  +
                                ", " + (100+i)  +
                                ", parsedatetime('2010-10-" + i + " 12:00:" + i + "', 'yyyy-MM-dd hh:mm:ss')" +
                                ", parsedatetime('2010-11-" + i + " 13:00:" + i + "', 'yyyy-MM-dd hh:mm:ss')" +
                                ")"
                ).executeUpdate();
            }

            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

}
